

// Sets up callbacks for state change
// You should not set up the state object until you get your first callback.
function init() {
   console.log("init");
   gapi.hangout.data.addStateChangeListener(listUpdated);
   gapi.hangout.data.addStateChangeListener(songUpdated);
   
   gapi.hangout.addParticipantsListener(participantsUpdated);
}



function listUpdated(delta, metadata){
	if(gapi.hangout.data.getState()['next_song']) {	     
		var data = gapi.hangout.data.getState()['next_song'].split("_");
		
		console.log("List Updated" + data);
		
		var song_name = data[0];
		var song_id = data[1];
		var singer = data[2];
		
		appendToPlaylist(song_name, song_id, singer);
		resetNext();
		
	}else{
		console.log("list undefined");
	}
}


function songUpdated(delta, metadata){
	if(gapi.hangout.data.getState()['now_playing']) {
	     
		var data = gapi.hangout.data.getState()['now_playing'];
		
		console.log("Song Updated " + data);

		swfobject.embedSWF("http://www.youtube.com/v/" + data + "?enablejsapi=1&playerapiid=ytplayer&version=3",
                       "player", "400", "300", "8", null, null, params, atts);
        
        
        window.setTimeout(  
    		function() {
    		console.log("PLAY");
       		play();  
    		},  
    	1000); 
        
        resetSong();
	}else{
		console.log("song undefined");
	}



}

function appendToPlaylist(song_name, song_id, singer){
	var html="<tr><td data-id=" + song_id + ">" + song_name + "</td><td>"+ singer +"</td></tr>";
	
	$(".playlist").append(html);	

}


function addSong(song_id, song_name ){
  	console.log("Button clicked addSong");
   	console.log( gapi.hangout.data.getState()['next_song'] );


	var id = gapi.hangout.getParticipantId();
	var name = gapi.hangout.getParticipantById(id).displayName;


	gapi.hangout.data.submitDelta({'next_song': song_name + "_" + song_id + "_" + name});
}

function songClicked(song_id) {
	console.log("Song Clicked");
	gapi.hangout.data.submitDelta({'now_playing': song_id});

}
       

// Note that the hangouts object is not set up until the gadget loads
gadgets.util.registerOnLoadHandler(init);
       
// Reset value of "count" to 0
function resetNext(){      
	console.log("reset next");
	gapi.hangout.data.submitDelta({'next_song': ''});
}

function resetSong(){      
	console.log("reset song");
	gapi.hangout.data.submitDelta({'now_playing': ''});
}